package com.itheima.reggie.controller;

import cn.hutool.Hutool;
import cn.hutool.http.HttpUtil;
import com.itheima.reggie.common.AliyunOSSUtil;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;



    //用户登录名称 reggieUpdate@1277363212969022.onaliyun.com
    //AccessKey ID LTAI5t5rB5kokzeNgSANgS8g
    //AccessKey Secret BFRDBcNBPEyBxlD9BZqhXAARcr9zZb

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {

        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String s = UUID.randomUUID() + substring;


        File file1 = new File(basePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        file.transferTo(new File(basePath + s));
        log.info("s-------------" + s);
        System.out.println(s);

        String s1 = AliyunOSSUtil.OSSUploadFile(basePath + s);

        log.info("---11111121123331221132121232312"+s1);
        System.out.println("---11111121123331221132121232312"+s1);
        //// 上传
        //// 填写Bucket名称，例如examplebucket。
        //String bucketName = "reggie-jiang";
        //// 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        //String objectName = "imgs/"+s;
        //ossClient.putObject(new PutObjectRequest(bucketName, objectName, new File(basePath + s)));
        //System.out.println("上传成功。。。");


        //// Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        //String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        //// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        //String accessKeyId = "LTAI5t5rB5kokzeNgSANgS8g";
        //String accessKeySecret = "BFRDBcNBPEyBxlD9BZqhXAARcr9zZb";
        //// 填写Bucket名称，例如examplebucket。
        //String bucketName = "reggie-jiang";
        //// 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        //String objectName = "imgs/"+s;
        //// 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        //// 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        //String filePath = basePath + s;
        //
        //// 创建OSSClient实例。
        //OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //
        //try {
        //    // 创建PutObjectRequest对象。
        //    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
        //    // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
        //    // ObjectMetadata metadata = new ObjectMetadata();
        //    // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        //    // metadata.setObjectAcl(CannedAccessControlList.Private);
        //    // putObjectRequest.setMetadata(metadata);
        //
        //    // 上传文件。
        //    ossClient.putObject(putObjectRequest);
        //    // 设置URL过期时间为6小时
        //
        //} catch (OSSException oe) {
        //    System.out.println("Caught an OSSException, which means your request made it to OSS, "
        //            + "but was rejected with an error response for some reason.");
        //    System.out.println("Error Message:" + oe.getErrorMessage());
        //    System.out.println("Error Code:" + oe.getErrorCode());
        //    System.out.println("Request ID:" + oe.getRequestId());
        //    System.out.println("Host ID:" + oe.getHostId());
        //} catch (ClientException ce) {
        //    System.out.println("Caught an ClientException, which means the client encountered "
        //            + "a serious internal problem while trying to communicate with OSS, "
        //            + "such as not being able to access the network.");
        //    System.out.println("Error Message:" + ce.getMessage());
        //} finally {
        //    if (ossClient != null) {
        //        ossClient.shutdown();
        //    }
        //}
        //Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000 * 6);
        //// 生成以GET方法访问的签名URL，可以直接通过浏览器访问相关内容
        //URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        //String s1 = url.toString();
        //log.info(s1);


        return R.success(s);

    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {

        try {
            //FileInputStream fis = new FileInputStream(basePath + name);
            //ServletOutputStream os = response.getOutputStream();
            //response.setContentType("image/jpeg");
            //int len = 0;
            //byte[] bytes = new byte[1024];
            //while ((len = fis.read(bytes)) != -1) {
            //    os.write(bytes, 0, len);
            //    os.flush();
            //}
            //os.close();
            //fis.close();
            ServletOutputStream out = response.getOutputStream();
            HttpUtil.download("https://reggie-jiang.oss-cn-hangzhou.aliyuncs.com/imgs/"+name,out,true);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
